<template>
	<view class="pages">
		<uni-segmented-control v-if="disabled" :current="current" :values="items" style-type="text" active-color="#2D82F6" @clickItem="onClickItem" style="margin-bottom: 20px;"/>
		<view v-if="current === 0">
			<uni-forms class="dialog-content" ref="valiForm" :modelValue="formData" :rules="rules">
        <uni-forms-item label="事件名称" name="eventName" required>
          <uni-easyinput :disabled="disabled" type="text" v-model="formData.eventName" maxlength="10" placeholder="请输入事件名称"/>
        </uni-forms-item>
				<uni-forms-item label="事件类型" name="eventTypeCode" required>
					<uni-easyinput type="text" style="display: none;" v-model="formData.eventTypeCode"/>
					<uni-data-picker v-if="!disabled" @change="onchangeType" v-model="formData.eventTypeCode"  popup-title="请选择事件类型" :localdata="eventTypeOptions" :map="{text:'typeName',value:'typeCode'}"></uni-data-picker>
					<uni-easyinput v-else :disabled="disabled" type="text" :value="formData.eventTypeName"/>
				</uni-forms-item>
        <uni-forms-item label="事件等级" name="eventLevelCode" required>
          <uni-easyinput type="text" style="display: none;" v-model="formData.eventLevelCode"/>
          <uni-data-picker v-if="!disabled" @change="onchangeLevel" v-model="formData.eventLevelCode"  popup-title="请选择事件类型" :localdata="eventLevelOptions"></uni-data-picker>
          <uni-easyinput v-else :disabled="disabled" type="text" :value="formData.eventLevelName"/>
        </uni-forms-item>
        <uni-forms-item v-if="!disabled" label="发生时间" required>
          <uni-datetime-picker type="datetime" :end="new Date()" v-model="formData.happenTime"/>
        </uni-forms-item>
        <uni-forms-item v-if="!disabled" label="定位" name="geom"  required>
          <uni-easyinput type="text" style="display: none;" v-model="formData.geom"/>
          <image @click="chooseLocation" style="width: 20px;height: 20px;margin-top: 5px;"  mode="aspectFit" src="../../static/icon/location.png" />
        </uni-forms-item>
        <uni-forms-item label="地址描述" name="locationDesc" required>
          <uni-easyinput :disabled="disabled" type="textarea" v-model="address" maxlength="50" placeholder="请输入地址描述"/>
        </uni-forms-item>
				<uni-forms-item label="事件描述" name="eventDesc">
					<uni-easyinput  :disabled="disabled" type="textarea" v-model="formData.eventDesc" maxlength="50" placeholder="请输入事件描述"/>
				</uni-forms-item>
				<uni-forms-item label="上传图片" v-if="!disabled">
					<uni-file-picker limit="3" ref="files" :auto-upload="false"></uni-file-picker>
				</uni-forms-item>
				<uni-forms-item label="图片"  v-if="disabled">
					<uni-file-picker :readonly="true"  :value="formData.pics|imagesFormat" limit="2" ref="files"></uni-file-picker>
				</uni-forms-item>
				<button type="primary" :hidden="disabled" @click="submit('valiForm')">提交</button>
			</uni-forms>
		</view>
		<view v-if="current === 1">
			<Liststeps v-for="(item, index) in stepList" :activity="item.done" :key="index" :index="index">
				<text slot="date" v-if="index == 0" style="color: #2D82F6;" >{{ item.date }}</text>
				<text slot="date" v-else >{{ item.date }}</text>
				<view slot="content">
					<view class="info_item" v-for="(info, index) in item.infoList" :key="index">
						<view class="label">{{ info.label }}</view>
						<view class="value"> {{ info.value }}{{ info.unit || '' }}</view>
					</view>
				</view>
				<view slot="content" style="margin-bottom: 20px;" v-if="item.pics.length > 0">
					<view class="info_item">
						<view class="label">附件</view>
						<view class="value">
							<uni-file-picker :readonly="true"  :value="item.pics|imagesFormat" limit="2" ref="files"></uni-file-picker>
						</view>
					</view>
				</view>
			</Liststeps>
		</view>
	</view>
</template>
<script>
	import { mapGetters } from 'vuex'
	import baseUrl from '../../config/baseUrl.js'
	import Liststeps from '../../components/lwp-step/lwp-step.vue'
  import { getTypeList,add,getHandleRecordList } from '../../api/event'
  import '../../common/util'
	let that = null
	export default {
		components: { Liststeps },
    computed: { ...mapGetters({ userInfo: 'userInfo' }) },
		data() {
			return {
				current: 0,
				disabled:false,
        address:'',
				items:['事件详情','处置记录'],
				stepList:[],
				eventTypeOptions:[],
        eventLevelOptions:[],
				formData:{ pics:[],happenTime: (new Date()).Format('yyyy-MM-dd HH:mm:ss') },
				rules: {
          eventName: {
						rules: [{
                required: true,
								errorMessage: '事件名称不能为空',
						}
					]
					},
          happenTime: {
						rules: [{
								required: true,
								errorMessage: '发生时间不能为空',
							}
						]
					},
          eventTypeCode: {
						rules: [{
								required: true,
								errorMessage: '请选择事件类型',
							}
						]
					},
          eventLevelCode: {
						rules: [{
								required: true,
								errorMessage: '请选择事件级别',
							}
						]
					},
          locationDesc: {
						rules: [{
								required: true,
								errorMessage: '地址描述不能为空',
							}
						]
					},
          geom: {
						rules: [{
								required: false,
								errorMessage: '请定位地址',
							}
						]
					}
				}
			}
		},
		created() {
		},
		onLoad(options) {
      that = this
			if(options.id != null){
				uni.setNavigationBarTitle({ title:'事件详情' })
				// 查看
				this.disabled = true
				uni.getStorage({
				    key:'eventDetail',
				    success:res=>{
						  this.formData = res.data
              this.address = res.data.locationDesc
              this.formData.pics = []
              let pics = JSON.parse(res.data.gatherPics)
              pics.forEach(item=>{
                this.formData.pics.push({
                  filePath:item.url,
                  imgName:item.name
                })
              })
					}
				})
        getHandleRecordList({ pageNum: 1,pageSize: 999,eventId:options.id }).then(res => {
					res.rows.forEach(item => {
            let pics = []
            if(item.gatherPics != null && item.gatherPics != '') {
              let json = JSON.parse(item.gatherPics)
              json.forEach(file => {
                pics.push({ filePath: file.url, fileName: file.name })
              })
            }
						this.stepList.push({
							date : item.handleTime.substring(5,16),
							businessId : item.replyId,
							done : false,
							infoList:[
								{
									label: '描述',
									value: item.handleContent
								},
								{
									label: '操作人',
									value: item.handleUserName
								}
							],
							pics:pics
						})
						this.stepList[0].done = true
					})
				}, err => {
				})
			}
      this.$http.getDicts('EVENT_LEVEL').then(res => {
        this.eventLevelOptions = res.data
      })
      getTypeList().then(res => {
				this.eventTypeOptions = res.rows
			})
		},	
		methods: {
      chooseLocation(){
        uni.chooseLocation({
          success: function (res) {
            var X_PI = Math.PI * 3000.0 / 180.0
            var x = res.longitude, y = res.latitude
            var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI)
            var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI)
            var bd_lng = z * Math.cos(theta) + 0.0065
            var bd_lat = z * Math.sin(theta) + 0.006
            that.formData.geom = bd_lng+','+bd_lat
            that.address = res.address
          }
        })
      },
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
      onchangeType(e) {
			  const select = e.detail.value[0]
			  this.formData.eventTypeName = select.text
			},
      onchangeLevel(e) {
			  const select = e.detail.value[0]
			  this.formData.eventLevelName = select.text
			},
			uploadPic(){
				let pics = []
				let token = this.userInfo.token
				let length = this.$refs.files.files.length
				let count = 0 
				return new Promise((resolve, reject)=>{
					this.$refs.files.files.forEach(function(item, index) {						
						let n = uni.uploadFile({
						    url: baseUrl.baseUrl +'/public/uploadAttachmentFile',
							header: { 'token': token },
						    filePath: item.url,
						    name: 'file',
						    success: uploadFileRes => {
								let json = JSON.parse(uploadFileRes.data)
								pics.push({
                  name:item.name,
                  url:json.data
                })
								count++
								if(count == length){
									resolve(pics)
								}
						    }
						})
					})
					
				})
			},
			async submit() {
				if(this.$refs.files.files.length > 0){
					let roadDiseaseSporPics = await this.uploadPic()
					this.formData.gatherPics = JSON.stringify(roadDiseaseSporPics)
				}
				this.$refs.valiForm.validate().then(res=>{
					this.formData.eventFlag = 0
          this.formData.locationDesc = this.address
					add(this.formData).then(res => {
						uni.showToast({
							title: '保存成功',
							duration: 1000
						})
						uni.navigateTo({ url:'./index' })
					})
				}).catch(err =>{
					console.log('表单错误信息：', err)
				})
			}
		}
	}
</script>


<style scoped lang="less">
	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}
	 
	.list {
		margin-bottom: 30rpx;
		background-color: #f9f9f9;
	}
	
	.diseaseList{
		font-size: 36rpx;
	}
	
	.diseaseList-header{
		color: #666666;
		flex-direction: row;
	}
	
	.info_item {
	  font-size: 28rpx;
	  font-weight: 400;
	  color: #949596;
	  display: flex;
	  .value {
		flex: 1;
		margin-left: 32rpx;
		font-size: 30rpx;
		font-weight: 400;
		color: #4a4d50;
	  }
	}
</style>
<style lang="scss" scoped>
	.pages {
		background-color: #FFFFFF;
	}
	.dialog-content{
		background-color: #fff;
		padding:10rpx 50rpx 30rpx;
		border-radius: 10rpx;
		font-size: 24rpx;
	}
</style>